<!-- 商品发布 - 库存价格 -->
<template>
  <el-form ref="formRef" :disabled="isDetail" :model="formData" :rules="rules" label-width="120px">
    <div
      class="p-10px border-rd-5px mb-20px border-1px flex flex-items-center bg-[var(--el-color-primary-light-9)] font-size-14px"
    >
      <span>规格属性</span>
      <Icon class="ml-5px" :icon="'ep:question-filled'" />
      <span class="ml-5px"> 不同规格商品的图片、零售价、成本价等不同的参数的设置 </span>
    </div>
    <!-- 多规格添加-->
    <el-form-item v-if="!formData.specType">
      <SkuList
        ref="skuListRef"
        :prop-form-data="formData"
        :property-list="propertyList"
        :rule-config="ruleConfig"
      />
    </el-form-item>
    <el-form-item v-if="formData.specType" label="商品规格">
      <ProductAttributes
        :is-detail="isDetail"
        :prop-form-data="formData"
        :property-list="propertyList"
        @success="generateSkus"
      />
      <el-button
        class="mb-10px mr-15px"
        v-if="propertyList.length == 0"
        @click="handleAttributesAdd"
        >添新加规格</el-button
      >
    </el-form-item>
    <template v-if="formData.specType && propertyList.length > 0">
      <el-form-item v-if="!isDetail" label="批量设置">
        <SkuList :is-batch="true" :prop-form-data="formData" :property-list="propertyList" />
      </el-form-item>
      <el-form-item label="规格列表">
        <SkuList
          ref="skuListRef"
          :is-detail="isDetail"
          :prop-form-data="formData"
          :property-list="propertyList"
          :rule-config="ruleConfig"
        />
      </el-form-item>
    </template>
  </el-form>
  <!-- 商品属性添加 Form 表单 -->
  <ProductPropertyAddForm ref="attributesAddFormRef" :propertyList="propertyList" />
</template>
<script lang="ts" setup>
import { PropType } from 'vue'
import { copyValueToTarget, generateSortNumericUUID } from '@/utils'
import { propTypes } from '@/utils/propTypes'
import { verifyNumberIntegerAndFloat } from '@/utils/formatter'

import {
  getPropertyList,
  PropertyAndValues,
  RuleConfig
} from '@/views/mall/product/spu/components/index'
import SkuList from './../components/SkuList.vue'
import ProductAttributes from '@/views/mall/product/spu/form/ProductAttributes.vue'
import ProductPropertyAddForm from '@/views/mall/product/spu/form/ProductPropertyAddForm.vue'
import type { Spu } from '@/api/mall/product/spu'
defineOptions({ name: 'ProductSpuVideoSkuForm' })

// sku 相关属性校验规则
const ruleConfig: RuleConfig[] = [
  {
    name: 'tvAssociatedMaterial',
    rule: (arg) => arg != undefined,
    message: '请关联素材 ！！！'
  }
]

const message = useMessage() // 消息弹窗

const props = defineProps({
  propFormData: {
    type: Object as PropType<Spu>,
    default: () => {}
  },
  isDetail: propTypes.bool.def(false), // 是否作为详情组件
  activeName: propTypes.string.def('sku')
})
const attributesAddFormRef = ref() // 添加商品属性表单
const formRef = ref() // 表单 Ref
const propertyList = ref<PropertyAndValues[]>([]) // 商品属性列表
const skuListRef = ref() // 商品属性列表 Ref
const formData = reactive<Spu>({
  specType: false, // 商品规格
  spuType: 6, //商品类型
  price: 0,
  marketPrice: 0, // 市场价
  costPrice: 0, // 成本价
  skus: [],
  salesChannel: [] //销售渠道
})
const handleAttributesAdd = () => {
  let data = {
    id: generateSortNumericUUID(),
    name: '',
    values: []
  }
  propertyList.value.push(data)
}
const rules = reactive({
  specType: [required],
  price: [required]
})
const attributesAddFormOpen = () => {
  attributesAddFormRef.value.open()
}
onMounted(() => {})
/** 将传进来的值赋值给 formData */
watch(
  () => props.propFormData,
  (data) => {
    if (!data) {
      return
    }
    copyValueToTarget(formData, data)
    // 将 SKU 的属性，整理成 PropertyAndValues 数组
    propertyList.value = getPropertyList(data)
  },
  {
    deep: true,
    immediate: true
  }
)

/** 表单校验 */
const emit = defineEmits(['update:activeName'])
const validate = async () => {
  if (!formRef) return
  try {
    // 校验 sku
    skuListRef.value?.validateSku()
    console.log(unref(formRef))
    await unref(formRef).validate()
    if (propertyList.value.length == 0) {
      emit('update:activeName', 'sku')

      throw '不完善，请填写相关信息' // 目的截断之后的校验
    }

    // 校验通过更新数据
    Object.assign(props.propFormData, formData)
  } catch (e) {
    message.error('【商品规格】不完善，请填写相关信息')
    emit('update:activeName', 'sku')
    throw e // 目的截断之后的校验
  }
}
defineExpose({ validate })

/** 调用 SkuList generateTableData 方法*/
const generateSkus = (propertyList: any[]) => {
  skuListRef.value.generateTableData(propertyList)
  Object.assign(props.propFormData, formData)
}
</script>
